// 资源 ：static  assets  
// 视图 ： views  templates  
// 数据 ： data  model   module
// util  public  common  src .... js  css  html
const http = require("http");
const fs = require("fs");
const url = require("url");
const mimeData = require("./data/mime.json");
const path = require("path");
let newsdata = require("./data/data.json");
let server = http.createServer((req,res)=>{
    let pathObj = url.parse(req.url,true);
    let pathname = pathObj.pathname;
    if(pathname == "/index" || pathname=="/"){
      let data =   fs.readFileSync("./views/index.html")
            res.write(data);
            res.end();
    }else if(pathname == "/detail"){
        let data =   fs.readFileSync("./views/detail.html")
        res.write(data);
        res.end();
    }else if(pathname == "/getdata"){
        res.write(JSON.stringify(newsdata));
        res.end();
    } else if(pathname == "/getdetail"){
        // 1.接收id  2.根据id 获取详细的数据
        let id = pathObj.query.id;
        console.log(id);
       let resdata =  newsdata.filter(item=>item.id==id)[0];
        res.write(JSON.stringify(resdata));
        res.end();

    } else{
        // 资源的处理
        if(req.url !== '/favicon.ico'){
            let extname = path.extname(req.url);
            res.setHeader("Content-Type",mimeData[extname]);
            let data =   fs.readFileSync("./static/"+req.url)
            res.write(data);
            res.end();
        }
    }
})

server.listen(8989);
